package cn.rxyb.boot.rabbitmq;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import cn.rxyb.boot.rabbitmq.enums.QueueEnums;
import cn.rxyb.boot.rabbitmq.mode.EventDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

/**
 * @author YJH
 * @version 1.0
 * @description rabbitmq 消息生产
 * @date 2020/7/3 11:00
 */
@Slf4j
public class RabbitmqProduction {


    private final RabbitTemplate rabbitTemplate;


    public RabbitmqProduction(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    /**
     * 消息发送
     *
     * @param dto
     * @return
     */
    public boolean send(final EventDto dto) {
        QueueEnums check = QueueEnums.check(dto.getEvent());
        if (null == check) {
            log.warn("未查询你要生产得队列[{}]", JSONUtil.toJsonStr(dto));
            return false;
        }
        // 判断是否是延迟队列
        if (check.getExchange().trim().equals("delay")) {
            if (dto.getDelayTime() <= 0L) {
                log.warn("生产延迟队列没有延迟时间队列[{}]", JSONUtil.toJsonStr(dto));
                return false;
            }
            // 队列生产
            rabbitTemplate.convertAndSend(check.getExchange(), check.getRouting(), dto, message -> {
                message.getMessageProperties().setDelay(dto.getDelayTime());
                return message;
            });
        }
        rabbitTemplate.convertAndSend(check.getExchange(), check.getRouting(), dto);
        return true;
    }
}
